home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / gdata / auth.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  35.7 KB  |  886 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import cgi
  5. import math
  6. import random
  7. import re
  8. import time
  9. import types
  10. import urllib
  11. import atom.http_interface as atom
  12. import atom.token_store as atom
  13. import atom.url as atom
  14. import gdata.oauth as oauth
  15. import gdata.oauth.rsa as oauth_rsa
  16. import gdata.tlslite.utils.keyfactory as keyfactory
  17. import gdata.tlslite.utils.cryptomath as cryptomath
  18. __author__ = 'api.jscudder (Jeff Scudder)'
  19. PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth='
  20. AUTHSUB_AUTH_LABEL = 'AuthSub token='
  21.  
  22. def generate_client_login_request_body(email, password, service, source, account_type = 'HOSTED_OR_GOOGLE', captcha_token = None, captcha_response = None):
  23.     """Creates the body of the autentication request
  24.  
  25.   See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request
  26.   for more details.
  27.  
  28.   Args:
  29.     email: str
  30.     password: str
  31.     service: str
  32.     source: str
  33.     account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid
  34.         values are 'GOOGLE' and 'HOSTED'
  35.     captcha_token: str (optional)
  36.     captcha_response: str (optional)
  37.  
  38.   Returns:
  39.     The HTTP body to send in a request for a client login token.
  40.   """
  41.     request_fields = {
  42.         'Email': email,
  43.         'Passwd': password,
  44.         'accountType': account_type,
  45.         'service': service,
  46.         'source': source }
  47.     if captcha_token and captcha_response:
  48.         request_fields['logintoken'] = captcha_token
  49.         request_fields['logincaptcha'] = captcha_response
  50.     
  51.     return urllib.urlencode(request_fields)
  52.  
  53. GenerateClientLoginRequestBody = generate_client_login_request_body
  54.  
  55. def GenerateClientLoginAuthToken(http_body):
  56.     """Returns the token value to use in Authorization headers.
  57.  
  58.   Reads the token from the server's response to a Client Login request and
  59.   creates header value to use in requests.
  60.  
  61.   Args:
  62.     http_body: str The body of the server's HTTP response to a Client Login
  63.         request
  64.  
  65.   Returns:
  66.     The value half of an Authorization header.
  67.   """
  68.     token = get_client_login_token(http_body)
  69.     if token:
  70.         return 'GoogleLogin auth=%s' % token
  71.  
  72.  
  73. def get_client_login_token(http_body):
  74.     """Returns the token value for a ClientLoginToken.
  75.  
  76.   Reads the token from the server's response to a Client Login request and
  77.   creates the token value string to use in requests.
  78.  
  79.   Args:
  80.     http_body: str The body of the server's HTTP response to a Client Login
  81.         request
  82.  
  83.   Returns:
  84.     The token value string for a ClientLoginToken.
  85.   """
  86.     for response_line in http_body.splitlines():
  87.         if response_line.startswith('Auth='):
  88.             return response_line[5:]
  89.     
  90.  
  91.  
  92. def extract_client_login_token(http_body, scopes):
  93.     """Parses the server's response and returns a ClientLoginToken.
  94.   
  95.   Args:
  96.     http_body: str The body of the server's HTTP response to a Client Login
  97.                request. It is assumed that the login request was successful.
  98.     scopes: list containing atom.url.Urls or strs. The scopes list contains
  99.             all of the partial URLs under which the client login token is
  100.             valid. For example, if scopes contains ['http://example.com/foo']
  101.             then the client login token would be valid for 
  102.             http://example.com/foo/bar/baz
  103.  
  104.   Returns:
  105.     A ClientLoginToken which is valid for the specified scopes.
  106.   """
  107.     token_string = get_client_login_token(http_body)
  108.     token = ClientLoginToken(scopes = scopes)
  109.     token.set_token_string(token_string)
  110.     return token
  111.  
  112.  
  113. def get_captcha_challenge(http_body, captcha_base_url = 'http://www.google.com/accounts/'):
  114.     """Returns the URL and token for a CAPTCHA challenge issued by the server.
  115.  
  116.   Args:
  117.     http_body: str The body of the HTTP response from the server which 
  118.         contains the CAPTCHA challenge.
  119.     captcha_base_url: str This function returns a full URL for viewing the 
  120.         challenge image which is built from the server's response. This
  121.         base_url is used as the beginning of the URL because the server
  122.         only provides the end of the URL. For example the server provides
  123.         'Captcha?ctoken=Hi...N' and the URL for the image is
  124.         'http://www.google.com/accounts/Captcha?ctoken=Hi...N'
  125.  
  126.   Returns:
  127.     A dictionary containing the information needed to repond to the CAPTCHA
  128.     challenge, the image URL and the ID token of the challenge. The 
  129.     dictionary is in the form:
  130.     {'token': string identifying the CAPTCHA image,
  131.      'url': string containing the URL of the image}
  132.     Returns None if there was no CAPTCHA challenge in the response.
  133.   """
  134.     contains_captcha_challenge = False
  135.     captcha_parameters = { }
  136.     for response_line in http_body.splitlines():
  137.         if response_line.startswith('Error=CaptchaRequired'):
  138.             contains_captcha_challenge = True
  139.             continue
  140.         if response_line.startswith('CaptchaToken='):
  141.             captcha_parameters['token'] = response_line[13:]
  142.             continue
  143.         if response_line.startswith('CaptchaUrl='):
  144.             captcha_parameters['url'] = '%s%s' % (captcha_base_url, response_line[11:])
  145.             continue
  146.     
  147.     if contains_captcha_challenge:
  148.         return captcha_parameters
  149.     return None
  150.  
  151. GetCaptchaChallenge = get_captcha_challenge
  152.  
  153. def GenerateOAuthRequestTokenUrl(oauth_input_params, scopes, request_token_url = 'https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters = None):
  154.     """Generate a URL at which a request for OAuth request token is to be sent.
  155.   
  156.   Args:
  157.     oauth_input_params: OAuthInputParams OAuth input parameters.
  158.     scopes: list of strings The URLs of the services to be accessed.
  159.     request_token_url: string The beginning of the request token URL. This is
  160.         normally 'https://www.google.com/accounts/OAuthGetRequestToken' or
  161.         '/accounts/OAuthGetRequestToken'
  162.     extra_parameters: dict (optional) key-value pairs as any additional
  163.         parameters to be included in the URL and signature while making a
  164.         request for fetching an OAuth request token. All the OAuth parameters
  165.         are added by default. But if provided through this argument, any
  166.         default parameters will be overwritten. For e.g. a default parameter
  167.         oauth_version 1.0 can be overwritten if
  168.         extra_parameters = {'oauth_version': '2.0'}
  169.   
  170.   Returns:
  171.     atom.url.Url OAuth request token URL.
  172.   """
  173.     scopes_string = []([ str(scope) for scope in scopes ])
  174.     parameters = {
  175.         'scope': scopes_string }
  176.     oauth_request = oauth.OAuthRequest.from_consumer_and_token(oauth_input_params.GetConsumer(), http_url = request_token_url, parameters = parameters)
  177.     oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), None)
  178.     return atom.url.parse_url(oauth_request.to_url())
  179.  
  180.  
  181. def GenerateOAuthAuthorizationUrl(request_token, authorization_url = 'https://www.google.com/accounts/OAuthAuthorizeToken', callback_url = None, extra_params = None, include_scopes_in_callback = False, scopes_param_prefix = 'oauth_token_scope'):
  182.     """Generates URL at which user will login to authorize the request token.
  183.   
  184.   Args:
  185.     request_token: gdata.auth.OAuthToken OAuth request token.
  186.     authorization_url: string The beginning of the authorization URL. This is
  187.         normally 'https://www.google.com/accounts/OAuthAuthorizeToken' or
  188.         '/accounts/OAuthAuthorizeToken'
  189.     callback_url: string (optional) The URL user will be sent to after
  190.         logging in and granting access.
  191.     extra_params: dict (optional) Additional parameters to be sent.
  192.     include_scopes_in_callback: Boolean (default=False) if set to True, and
  193.         if 'callback_url' is present, the 'callback_url' will be modified to
  194.         include the scope(s) from the request token as a URL parameter. The
  195.         key for the 'callback' URL's scope parameter will be
  196.         OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as
  197.         a parameter to the 'callback' URL, is that the page which receives
  198.         the OAuth token will be able to tell which URLs the token grants
  199.         access to.
  200.     scopes_param_prefix: string (default='oauth_token_scope') The URL
  201.         parameter key which maps to the list of valid scopes for the token.
  202.         This URL parameter will be included in the callback URL along with
  203.         the scopes of the token as value if include_scopes_in_callback=True.
  204.  
  205.   Returns:
  206.     atom.url.Url OAuth authorization URL.
  207.   """
  208.     scopes = request_token.scopes
  209.     if isinstance(scopes, list):
  210.         scopes = ' '.join(scopes)
  211.     
  212.     if include_scopes_in_callback and callback_url:
  213.         if callback_url.find('?') > -1:
  214.             callback_url += '&'
  215.         else:
  216.             callback_url += '?'
  217.         callback_url += urllib.urlencode({
  218.             scopes_param_prefix: scopes })
  219.     
  220.     oauth_token = oauth.OAuthToken(request_token.key, request_token.secret)
  221.     oauth_request = oauth.OAuthRequest.from_token_and_callback(token = oauth_token, callback = callback_url, http_url = authorization_url, parameters = extra_params)
  222.     return atom.url.parse_url(oauth_request.to_url())
  223.  
  224.  
  225. def GenerateOAuthAccessTokenUrl(authorized_request_token, oauth_input_params, access_token_url = 'https://www.google.com/accounts/OAuthGetAccessToken', oauth_version = '1.0'):
  226.     """Generates URL at which user will login to authorize the request token.
  227.   
  228.   Args:
  229.     authorized_request_token: gdata.auth.OAuthToken OAuth authorized request
  230.         token.
  231.     oauth_input_params: OAuthInputParams OAuth input parameters.    
  232.     access_token_url: string The beginning of the authorization URL. This is
  233.         normally 'https://www.google.com/accounts/OAuthGetAccessToken' or
  234.         '/accounts/OAuthGetAccessToken'
  235.     oauth_version: str (default='1.0') oauth_version parameter.
  236.  
  237.   Returns:
  238.     atom.url.Url OAuth access token URL.
  239.   """
  240.     oauth_token = oauth.OAuthToken(authorized_request_token.key, authorized_request_token.secret)
  241.     oauth_request = oauth.OAuthRequest.from_consumer_and_token(oauth_input_params.GetConsumer(), token = oauth_token, http_url = access_token_url, parameters = {
  242.         'oauth_version': oauth_version })
  243.     oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), oauth_token)
  244.     return atom.url.parse_url(oauth_request.to_url())
  245.  
  246.  
  247. def GenerateAuthSubUrl(next, scope, secure = False, session = True, request_url = 'https://www.google.com/accounts/AuthSubRequest', domain = 'default'):
  248.     """Generate a URL at which the user will login and be redirected back.
  249.  
  250.   Users enter their credentials on a Google login page and a token is sent
  251.   to the URL specified in next. See documentation for AuthSub login at:
  252.   http://code.google.com/apis/accounts/AuthForWebApps.html
  253.  
  254.   Args:
  255.     request_url: str The beginning of the request URL. This is normally
  256.         'http://www.google.com/accounts/AuthSubRequest' or 
  257.         '/accounts/AuthSubRequest'
  258.     next: string The URL user will be sent to after logging in.
  259.     scope: string The URL of the service to be accessed.
  260.     secure: boolean (optional) Determines whether or not the issued token
  261.             is a secure token.
  262.     session: boolean (optional) Determines whether or not the issued token
  263.              can be upgraded to a session token.
  264.     domain: str (optional) The Google Apps domain for this account. If this
  265.             is not a Google Apps account, use 'default' which is the default
  266.             value.
  267.   """
  268.     if secure:
  269.         secure = 1
  270.     else:
  271.         secure = 0
  272.     if session:
  273.         session = 1
  274.     else:
  275.         session = 0
  276.     request_params = urllib.urlencode({
  277.         'next': next,
  278.         'scope': scope,
  279.         'secure': secure,
  280.         'session': session,
  281.         'hd': domain })
  282.     if request_url.find('?') == -1:
  283.         return '%s?%s' % (request_url, request_params)
  284.     return '%s&%s' % (request_url, request_params)
  285.  
  286.  
  287. def generate_auth_sub_url(next, scopes, secure = False, session = True, request_url = 'https://www.google.com/accounts/AuthSubRequest', domain = 'default', scopes_param_prefix = 'auth_sub_scopes'):
  288.     """Constructs a URL string for requesting a multiscope AuthSub token.
  289.  
  290.   The generated token will contain a URL parameter to pass along the 
  291.   requested scopes to the next URL. When the Google Accounts page 
  292.   redirects the broswser to the 'next' URL, it appends the single use
  293.   AuthSub token value to the URL as a URL parameter with the key 'token'.
  294.   However, the information about which scopes were requested is not
  295.   included by Google Accounts. This method adds the scopes to the next
  296.   URL before making the request so that the redirect will be sent to 
  297.   a page, and both the token value and the list of scopes can be 
  298.   extracted from the request URL. 
  299.  
  300.   Args:
  301.     next: atom.url.URL or string The URL user will be sent to after
  302.           authorizing this web application to access their data.
  303.     scopes: list containint strings The URLs of the services to be accessed.
  304.     secure: boolean (optional) Determines whether or not the issued token
  305.             is a secure token.
  306.     session: boolean (optional) Determines whether or not the issued token
  307.              can be upgraded to a session token.
  308.     request_url: atom.url.Url or str The beginning of the request URL. This
  309.         is normally 'http://www.google.com/accounts/AuthSubRequest' or 
  310.         '/accounts/AuthSubRequest'
  311.     domain: The domain which the account is part of. This is used for Google
  312.         Apps accounts, the default value is 'default' which means that the
  313.         requested account is a Google Account (@gmail.com for example)
  314.     scopes_param_prefix: str (optional) The requested scopes are added as a 
  315.         URL parameter to the next URL so that the page at the 'next' URL can
  316.         extract the token value and the valid scopes from the URL. The key
  317.         for the URL parameter defaults to 'auth_sub_scopes'
  318.  
  319.   Returns:
  320.     An atom.url.Url which the user's browser should be directed to in order
  321.     to authorize this application to access their information.
  322.   """
  323.     if isinstance(next, (str, unicode)):
  324.         next = atom.url.parse_url(next)
  325.     
  326.     scopes_string = []([ str(scope) for scope in scopes ])
  327.     next.params[scopes_param_prefix] = scopes_string
  328.     request_url.params['next'] = str(next)
  329.     request_url.params['scope'] = scopes_string
  330.     if session:
  331.         request_url.params['session'] = 1
  332.     else:
  333.         request_url.params['session'] = 0
  334.     if secure:
  335.         request_url.params['secure'] = 1
  336.     else:
  337.         request_url.params['secure'] = 0
  338.     request_url.params['hd'] = domain
  339.     return request_url
  340.  
  341.  
  342. def AuthSubTokenFromUrl(url):
  343.     """Extracts the AuthSub token from the URL. 
  344.  
  345.   Used after the AuthSub redirect has sent the user to the 'next' page and
  346.   appended the token to the URL. This function returns the value to be used
  347.   in the Authorization header. 
  348.  
  349.   Args:
  350.     url: str The URL of the current page which contains the AuthSub token as
  351.         a URL parameter.
  352.   """
  353.     token = TokenFromUrl(url)
  354.     if token:
  355.         return 'AuthSub token=%s' % token
  356.  
  357.  
  358. def TokenFromUrl(url):
  359.     '''Extracts the AuthSub token from the URL.
  360.  
  361.   Returns the raw token value.
  362.  
  363.   Args:
  364.     url: str The URL or the query portion of the URL string (after the ?) of
  365.         the current page which contains the AuthSub token as a URL parameter.
  366.   '''
  367.     if url.find('?') > -1:
  368.         query_params = url.split('?')[1]
  369.     else:
  370.         query_params = url
  371.     for pair in query_params.split('&'):
  372.         if pair.startswith('token='):
  373.             return pair[6:]
  374.     
  375.  
  376.  
  377. def extract_auth_sub_token_from_url(url, scopes_param_prefix = 'auth_sub_scopes', rsa_key = None):
  378.     """Creates an AuthSubToken and sets the token value and scopes from the URL.
  379.   
  380.   After the Google Accounts AuthSub pages redirect the user's broswer back to 
  381.   the web application (using the 'next' URL from the request) the web app must
  382.   extract the token from the current page's URL. The token is provided as a 
  383.   URL parameter named 'token' and if generate_auth_sub_url was used to create
  384.   the request, the token's valid scopes are included in a URL parameter whose
  385.   name is specified in scopes_param_prefix.
  386.  
  387.   Args:
  388.     url: atom.url.Url or str representing the current URL. The token value
  389.          and valid scopes should be included as URL parameters.
  390.     scopes_param_prefix: str (optional) The URL parameter key which maps to
  391.                          the list of valid scopes for the token.
  392.  
  393.   Returns:
  394.     An AuthSubToken with the token value from the URL and set to be valid for
  395.     the scopes passed in on the URL. If no scopes were included in the URL,
  396.     the AuthSubToken defaults to being valid for no scopes. If there was no
  397.     'token' parameter in the URL, this function returns None.
  398.   """
  399.     if isinstance(url, (str, unicode)):
  400.         url = atom.url.parse_url(url)
  401.     
  402.     if 'token' not in url.params:
  403.         return None
  404.     scopes = []
  405.     if scopes_param_prefix in url.params:
  406.         scopes = url.params[scopes_param_prefix].split(' ')
  407.     
  408.     token_value = url.params['token']
  409.     if rsa_key:
  410.         token = SecureAuthSubToken(rsa_key, scopes = scopes)
  411.     else:
  412.         token = AuthSubToken(scopes = scopes)
  413.     token.set_token_string(token_value)
  414.     return token
  415.  
  416.  
  417. def AuthSubTokenFromHttpBody(http_body):
  418.     """Extracts the AuthSub token from an HTTP body string.
  419.  
  420.   Used to find the new session token after making a request to upgrade a
  421.   single use AuthSub token.
  422.  
  423.   Args:
  424.     http_body: str The repsonse from the server which contains the AuthSub
  425.         key. For example, this function would find the new session token
  426.         from the server's response to an upgrade token request.
  427.  
  428.   Returns:
  429.     The header value to use for Authorization which contains the AuthSub
  430.     token.
  431.   """
  432.     token_value = token_from_http_body(http_body)
  433.     if token_value:
  434.         return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value)
  435.  
  436.  
  437. def token_from_http_body(http_body):
  438.     """Extracts the AuthSub token from an HTTP body string.
  439.  
  440.   Used to find the new session token after making a request to upgrade a 
  441.   single use AuthSub token.
  442.  
  443.   Args:
  444.     http_body: str The repsonse from the server which contains the AuthSub 
  445.         key. For example, this function would find the new session token
  446.         from the server's response to an upgrade token request.
  447.  
  448.   Returns:
  449.     The raw token value to use in an AuthSubToken object.
  450.   """
  451.     for response_line in http_body.splitlines():
  452.         if response_line.startswith('Token='):
  453.             return response_line[6:]
  454.     
  455.  
  456. TokenFromHttpBody = token_from_http_body
  457.  
  458. def OAuthTokenFromUrl(url, scopes_param_prefix = 'oauth_token_scope'):
  459.     """Creates an OAuthToken and sets token key and scopes (if present) from URL.
  460.   
  461.   After the Google Accounts OAuth pages redirect the user's broswer back to 
  462.   the web application (using the 'callback' URL from the request) the web app
  463.   can extract the token from the current page's URL. The token is same as the
  464.   request token, but it is either authorized (if user grants access) or
  465.   unauthorized (if user denies access). The token is provided as a 
  466.   URL parameter named 'oauth_token' and if it was chosen to use
  467.   GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's
  468.   valid scopes are included in a URL parameter whose name is specified in
  469.   scopes_param_prefix.
  470.  
  471.   Args:
  472.     url: atom.url.Url or str representing the current URL. The token value
  473.         and valid scopes should be included as URL parameters.
  474.     scopes_param_prefix: str (optional) The URL parameter key which maps to
  475.         the list of valid scopes for the token.
  476.  
  477.   Returns:
  478.     An OAuthToken with the token key from the URL and set to be valid for
  479.     the scopes passed in on the URL. If no scopes were included in the URL,
  480.     the OAuthToken defaults to being valid for no scopes. If there was no
  481.     'oauth_token' parameter in the URL, this function returns None.
  482.   """
  483.     if isinstance(url, (str, unicode)):
  484.         url = atom.url.parse_url(url)
  485.     
  486.     if 'oauth_token' not in url.params:
  487.         return None
  488.     scopes = []
  489.     if scopes_param_prefix in url.params:
  490.         scopes = url.params[scopes_param_prefix].split(' ')
  491.     
  492.     token_key = url.params['oauth_token']
  493.     token = OAuthToken(key = token_key, scopes = scopes)
  494.     return token
  495.  
  496.  
  497. def OAuthTokenFromHttpBody(http_body):
  498.     """Parses the HTTP response body and returns an OAuth token.
  499.   
  500.   The returned OAuth token will just have key and secret parameters set.
  501.   It won't have any knowledge about the scopes or oauth_input_params. It is
  502.   your responsibility to make it aware of the remaining parameters.
  503.   
  504.   Returns:
  505.     OAuthToken OAuth token.
  506.   """
  507.     token = oauth.OAuthToken.from_string(http_body)
  508.     oauth_token = OAuthToken(key = token.key, secret = token.secret)
  509.     return oauth_token
  510.  
  511.  
  512. class OAuthSignatureMethod(object):
  513.     '''Holds valid OAuth signature methods.
  514.   
  515.   RSA_SHA1: Class to build signature according to RSA-SHA1 algorithm.
  516.   HMAC_SHA1: Class to build signature according to HMAC-SHA1 algorithm.
  517.   '''
  518.     HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1
  519.     
  520.     class RSA_SHA1(oauth_rsa.OAuthSignatureMethod_RSA_SHA1):
  521.         '''Provides implementation for abstract methods to return RSA certs.'''
  522.         
  523.         def __init__(self, private_key, public_cert):
  524.             self.private_key = private_key
  525.             self.public_cert = public_cert
  526.  
  527.         
  528.         def _fetch_public_cert(self, unused_oauth_request):
  529.             return self.public_cert
  530.  
  531.         
  532.         def _fetch_private_cert(self, unused_oauth_request):
  533.             return self.private_key
  534.  
  535.  
  536.  
  537.  
  538. class OAuthInputParams(object):
  539.     '''Stores OAuth input parameters.
  540.   
  541.   This class is a store for OAuth input parameters viz. consumer key and secret,
  542.   signature method and RSA key.
  543.   '''
  544.     
  545.     def __init__(self, signature_method, consumer_key, consumer_secret = None, rsa_key = None):
  546.         '''Initializes object with parameters required for using OAuth mechanism.
  547.     
  548.     NOTE: Though consumer_secret and rsa_key are optional, either of the two
  549.     is required depending on the value of the signature_method.
  550.     
  551.     Args:
  552.       signature_method: class which provides implementation for strategy class
  553.           oauth.oauth.OAuthSignatureMethod. Signature method to be used for
  554.           signing each request. Valid implementations are provided as the
  555.           constants defined by gdata.auth.OAuthSignatureMethod. Currently
  556.           they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and
  557.           gdata.auth.OAuthSignatureMethod.HMAC_SHA1
  558.       consumer_key: string Domain identifying third_party web application.
  559.       consumer_secret: string (optional) Secret generated during registration.
  560.           Required only for HMAC_SHA1 signature method.
  561.       rsa_key: string (optional) Private key required for RSA_SHA1 signature
  562.           method.
  563.     '''
  564.         if signature_method == OAuthSignatureMethod.RSA_SHA1:
  565.             self._signature_method = signature_method(rsa_key, None)
  566.         else:
  567.             self._signature_method = signature_method()
  568.         self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
  569.  
  570.     
  571.     def GetSignatureMethod(self):
  572.         '''Gets the OAuth signature method.
  573.  
  574.     Returns:
  575.       object of supertype <oauth.oauth.OAuthSignatureMethod>
  576.     '''
  577.         return self._signature_method
  578.  
  579.     
  580.     def GetConsumer(self):
  581.         '''Gets the OAuth consumer.
  582.     
  583.     Returns:
  584.       object of type <oauth.oauth.Consumer>
  585.     '''
  586.         return self._consumer
  587.  
  588.  
  589.  
  590. class ClientLoginToken(atom.http_interface.GenericToken):
  591.     """Stores the Authorization header in auth_header and adds to requests.
  592.  
  593.   This token will add it's Authorization header to an HTTP request
  594.   as it is made. Ths token class is simple but
  595.   some Token classes must calculate portions of the Authorization header
  596.   based on the request being made, which is why the token is responsible
  597.   for making requests via an http_client parameter.
  598.  
  599.   Args:
  600.     auth_header: str The value for the Authorization header.
  601.     scopes: list of str or atom.url.Url specifying the beginnings of URLs
  602.         for which this token can be used. For example, if scopes contains
  603.         'http://example.com/foo', then this token can be used for a request to
  604.         'http://example.com/foo/bar' but it cannot be used for a request to
  605.         'http://example.com/baz'
  606.   """
  607.     
  608.     def __init__(self, auth_header = None, scopes = None):
  609.         self.auth_header = auth_header
  610.         if not scopes:
  611.             pass
  612.         self.scopes = []
  613.  
  614.     
  615.     def __str__(self):
  616.         return self.auth_header
  617.  
  618.     
  619.     def perform_request(self, http_client, operation, url, data = None, headers = None):
  620.         '''Sets the Authorization header and makes the HTTP request.'''
  621.         if headers is None:
  622.             headers = {
  623.                 'Authorization': self.auth_header }
  624.         else:
  625.             headers['Authorization'] = self.auth_header
  626.         return http_client.request(operation, url, data = data, headers = headers)
  627.  
  628.     
  629.     def get_token_string(self):
  630.         '''Removes PROGRAMMATIC_AUTH_LABEL to give just the token value.'''
  631.         return self.auth_header[len(PROGRAMMATIC_AUTH_LABEL):]
  632.  
  633.     
  634.     def set_token_string(self, token_string):
  635.         self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string)
  636.  
  637.     
  638.     def valid_for_scope(self, url):
  639.         '''Tells the caller if the token authorizes access to the desired URL.
  640.     '''
  641.         if isinstance(url, (str, unicode)):
  642.             url = atom.url.parse_url(url)
  643.         
  644.         for scope in self.scopes:
  645.             if scope == atom.token_store.SCOPE_ALL:
  646.                 return True
  647.             if isinstance(scope, (str, unicode)):
  648.                 scope = atom.url.parse_url(scope)
  649.             
  650.             if scope == url:
  651.                 return True
  652.             if scope.host == url.host and not (scope.path):
  653.                 return True
  654.             if scope.host == url.host and scope.path and not (url.path):
  655.                 continue
  656.                 continue
  657.             not (scope.path)
  658.             if scope.host == url.host and url.path.startswith(scope.path):
  659.                 return True
  660.         
  661.         return False
  662.  
  663.  
  664.  
  665. class AuthSubToken(ClientLoginToken):
  666.     
  667.     def get_token_string(self):
  668.         '''Removes AUTHSUB_AUTH_LABEL to give just the token value.'''
  669.         return self.auth_header[len(AUTHSUB_AUTH_LABEL):]
  670.  
  671.     
  672.     def set_token_string(self, token_string):
  673.         self.auth_header = '%s%s' % (AUTHSUB_AUTH_LABEL, token_string)
  674.  
  675.  
  676.  
  677. class OAuthToken(atom.http_interface.GenericToken):
  678.     """Stores the token key, token secret and scopes for which token is valid.
  679.   
  680.   This token adds the authorization header to each request made. It
  681.   re-calculates authorization header for every request since the OAuth
  682.   signature to be added to the authorization header is dependent on the
  683.   request parameters.
  684.   
  685.   Attributes:
  686.     key: str The value for the OAuth token i.e. token key.
  687.     secret: str The value for the OAuth token secret.
  688.     scopes: list of str or atom.url.Url specifying the beginnings of URLs
  689.         for which this token can be used. For example, if scopes contains
  690.         'http://example.com/foo', then this token can be used for a request to
  691.         'http://example.com/foo/bar' but it cannot be used for a request to
  692.         'http://example.com/baz'
  693.     oauth_input_params: OAuthInputParams OAuth input parameters.      
  694.   """
  695.     
  696.     def __init__(self, key = None, secret = None, scopes = None, oauth_input_params = None):
  697.         self.key = key
  698.         self.secret = secret
  699.         if not scopes:
  700.             pass
  701.         self.scopes = []
  702.         self.oauth_input_params = oauth_input_params
  703.  
  704.     
  705.     def __str__(self):
  706.         return self.get_token_string()
  707.  
  708.     
  709.     def get_token_string(self):
  710.         '''Returns the token string.
  711.     
  712.     The token string returned is of format
  713.     oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings.
  714.     
  715.     Returns:
  716.       A token string of format oauth_token=[0]&oauth_token_secret=[1],
  717.       where [0] and [1] are some strings. If self.secret is absent, it just
  718.       returns oauth_token=[0]. If self.key is absent, it just returns
  719.       oauth_token_secret=[1]. If both are absent, it returns None.
  720.     '''
  721.         if self.key and self.secret:
  722.             return urllib.urlencode({
  723.                 'oauth_token': self.key,
  724.                 'oauth_token_secret': self.secret })
  725.         if self.key:
  726.             return 'oauth_token=%s' % self.key
  727.         if self.secret:
  728.             return 'oauth_token_secret=%s' % self.secret
  729.         return None
  730.  
  731.     
  732.     def set_token_string(self, token_string):
  733.         '''Sets the token key and secret from the token string.
  734.     
  735.     Args:
  736.       token_string: str Token string of form
  737.           oauth_token=[0]&oauth_token_secret=[1]. If oauth_token is not present,
  738.           self.key will be None. If oauth_token_secret is not present,
  739.           self.secret will be None.
  740.     '''
  741.         token_params = cgi.parse_qs(token_string, keep_blank_values = False)
  742.         if 'oauth_token' in token_params:
  743.             self.key = token_params['oauth_token'][0]
  744.         
  745.         if 'oauth_token_secret' in token_params:
  746.             self.secret = token_params['oauth_token_secret'][0]
  747.         
  748.  
  749.     
  750.     def GetAuthHeader(self, http_method, http_url, realm = ''):
  751.         """Get the authentication header.
  752.  
  753.     Args:
  754.       http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
  755.       http_url: string or atom.url.Url HTTP URL to which request is made.
  756.       realm: string (default='') realm parameter to be included in the
  757.           authorization header.
  758.  
  759.     Returns:
  760.       dict Header to be sent with every subsequent request after
  761.       authentication.
  762.     """
  763.         if isinstance(http_url, types.StringTypes):
  764.             http_url = atom.url.parse_url(http_url)
  765.         
  766.         header = None
  767.         token = None
  768.         if self.key or self.secret:
  769.             token = oauth.OAuthToken(self.key, self.secret)
  770.         
  771.         oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.oauth_input_params.GetConsumer(), token = token, http_url = str(http_url), http_method = http_method, parameters = http_url.params)
  772.         oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(), self.oauth_input_params.GetConsumer(), token)
  773.         header = oauth_request.to_header(realm = realm)
  774.         header['Authorization'] = header['Authorization'].replace('+', '%2B')
  775.         return header
  776.  
  777.     
  778.     def perform_request(self, http_client, operation, url, data = None, headers = None):
  779.         '''Sets the Authorization header and makes the HTTP request.'''
  780.         if not headers:
  781.             headers = { }
  782.         
  783.         headers.update(self.GetAuthHeader(operation, url))
  784.         return http_client.request(operation, url, data = data, headers = headers)
  785.  
  786.     
  787.     def valid_for_scope(self, url):
  788.         if isinstance(url, (str, unicode)):
  789.             url = atom.url.parse_url(url)
  790.         
  791.         for scope in self.scopes:
  792.             if scope == atom.token_store.SCOPE_ALL:
  793.                 return True
  794.             if isinstance(scope, (str, unicode)):
  795.                 scope = atom.url.parse_url(scope)
  796.             
  797.             if scope == url:
  798.                 return True
  799.             if scope.host == url.host and not (scope.path):
  800.                 return True
  801.             if scope.host == url.host and scope.path and not (url.path):
  802.                 continue
  803.                 continue
  804.             not (scope.path)
  805.             if scope.host == url.host and url.path.startswith(scope.path):
  806.                 return True
  807.         
  808.         return False
  809.  
  810.  
  811.  
  812. class SecureAuthSubToken(AuthSubToken):
  813.     """Stores the rsa private key, token, and scopes for the secure AuthSub token.
  814.   
  815.   This token adds the authorization header to each request made. It
  816.   re-calculates authorization header for every request since the secure AuthSub
  817.   signature to be added to the authorization header is dependent on the
  818.   request parameters.
  819.   
  820.   Attributes:
  821.     rsa_key: string The RSA private key in PEM format that the token will
  822.              use to sign requests
  823.     token_string: string (optional) The value for the AuthSub token.
  824.     scopes: list of str or atom.url.Url specifying the beginnings of URLs
  825.         for which this token can be used. For example, if scopes contains
  826.         'http://example.com/foo', then this token can be used for a request to
  827.         'http://example.com/foo/bar' but it cannot be used for a request to
  828.         'http://example.com/baz'     
  829.   """
  830.     
  831.     def __init__(self, rsa_key, token_string = None, scopes = None):
  832.         self.rsa_key = keyfactory.parsePEMKey(rsa_key)
  833.         if not token_string:
  834.             pass
  835.         self.token_string = ''
  836.         if not scopes:
  837.             pass
  838.         self.scopes = []
  839.  
  840.     
  841.     def __str__(self):
  842.         return self.get_token_string()
  843.  
  844.     
  845.     def get_token_string(self):
  846.         return str(self.token_string)
  847.  
  848.     
  849.     def set_token_string(self, token_string):
  850.         self.token_string = token_string
  851.  
  852.     
  853.     def GetAuthHeader(self, http_method, http_url):
  854.         '''Generates the Authorization header.
  855.  
  856.     The form of the secure AuthSub Authorization header is
  857.     Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig"
  858.     and  data represents a string in the form
  859.     data = http_method http_url timestamp nonce
  860.  
  861.     Args:
  862.       http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
  863.       http_url: string or atom.url.Url HTTP URL to which request is made.
  864.       
  865.     Returns:
  866.       dict Header to be sent with every subsequent request after authentication.
  867.     '''
  868.         timestamp = int(math.floor(time.time()))
  869.         nonce = '%lu' % random.randrange(1, 0x10000000000000000L)
  870.         data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce)
  871.         sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data))
  872.         header = {
  873.             'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' % (AUTHSUB_AUTH_LABEL, self.token_string, data, sig) }
  874.         return header
  875.  
  876.     
  877.     def perform_request(self, http_client, operation, url, data = None, headers = None):
  878.         '''Sets the Authorization header and makes the HTTP request.'''
  879.         if not headers:
  880.             headers = { }
  881.         
  882.         headers.update(self.GetAuthHeader(operation, url))
  883.         return http_client.request(operation, url, data = data, headers = headers)
  884.  
  885.  
  886.